package com.kuangjia.boss.commonSafety;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.security.Key;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 * AES加密-用于签名 - Util
 * </p>
 *
 * @author JiangYiji
 * @since 2024/12/04
 */
@Slf4j
public class AESEncryption {

    public static String password = "yjkjh@7355608!dpmhsgk@7355608!dpm";

    /**
     * 加密文件
     */
    public static boolean encryptFile(MultipartFile inputFile, String outputFilePath) {
        try {
            // 获取输入流
            byte[] fileBytes = inputFile.getBytes();
            // 生成AES密钥
            Key aesKey = new SecretKeySpec(password.getBytes(), "AES");
            // 创建AES加密器
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, aesKey);
            byte[] encryptedBytes = cipher.doFinal(fileBytes);
            // 将加密后的数据写入指定路径的输出文件
            try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
                fos.write(encryptedBytes);
            }
            return true;
        } catch (Exception e) {
            log.error("加密文件失败", e);
            return false;
        }
    }



    public static void encryptVideoFile(String inputFilePath, String outputFilePath, String password) throws Exception {
        // 读取视频文件
        byte[] fileBytes = Files.readAllBytes(new File(inputFilePath).toPath());
        // 生成AES密钥
        Key aesKey = new SecretKeySpec(password.getBytes(), "AES");
        // 加密
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, aesKey);
        byte[] encryptedBytes = cipher.doFinal(fileBytes);
        // 将加密后的数据写入新文件
        try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
            fos.write(encryptedBytes);
        }
    }

    public static void main(String[] args) {
        try {
            String inputFilePath = "D:\\加密文件夹\\111.mp4";
            String outputFilePath = "D:\\加密文件夹\\111.mp4";
            encryptVideoFile(inputFilePath, outputFilePath, password);
            System.out.println("Video file encrypted successfully.");
        } catch (Exception e) {
            e.printStackTrace();
        }
//
        try {
            String inputFilePath = "D:\\加密文件夹\\111.jpg";
            String outputFilePath = "D:\\加密文件夹\\111.jpg";
            encryptVideoFile(inputFilePath, outputFilePath, password);
            System.out.println("Video file encrypted successfully.");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}